﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using JHMVVMFramework.Common.Command;
using System.Collections.Specialized;

namespace JHMVVMFramework.Common.Command
{
    public class CommandArgs:DependencyObjectCollection<CommandArg>
    {
        public CommandArgs()
            : base()
        {
            base.Clear();
            base.CollectionChanged += new System.Collections.Specialized.NotifyCollectionChangedEventHandler(CommandArgs_CollectionChanged);
        }

        private void CommandArgs_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
        {
            if (e.Action == NotifyCollectionChangedAction.Add && e.NewItems != null)
            {
                foreach (CommandArg arg in e.NewItems)
                {
                    CommandArg containArg = GetItemByKey(arg.Key);

                    if (containArg != null && !containArg.Equals(arg))
                    {
                        throw new Exception("The collection contains this key");
                    }
                }
            }
        }

        public new void Add(CommandArg item)
        {

            if (GetItemByKey(item.Key) != null)
            {
                throw new Exception("The collection contains this key");
            }
            else
            {
                base.Add(item);
            }
        }


        private CommandArg GetItemByKey(string key)
        {
            if (!String.IsNullOrEmpty(key) && !String.IsNullOrWhiteSpace(key))
            {
                for (int i = 0; i < base.Count; i++)
                {
                    CommandArg arg = base[i];
                    if (arg.Key == key)
                    {
                        return arg;
                    }
                }
            }
            return null;
        }

        /// <summary>
        /// 索引器
        /// </summary>
        /// <param name="key">Key</param>
        /// <returns></returns>
        public CommandArg this[string key]
        {
            get
            {
                return GetItemByKey(key);
            }
            set
            {
                CommandArg arg = GetItemByKey(key);
                if (arg == null)
                {
                    throw new NullReferenceException();
                }
                else
                {
                    arg = value;
                }
            }
        }
    }
}
